<?php

declare (strict_types = 1);

namespace app\adminapi\controller;

use app\common\util\ApiResponseTrait;
use app\common\service\permission\AdminService;
use app\common\util\JwtUtil;
use Gregwar\Captcha\CaptchaBuilder;
use app\adminapi\validate\AdminValidate;
use think\Request;
use think\facade\Cache;

class Auth
{
    use ApiResponseTrait;

    /**
     * 登录
     * 
     * @param AdminValidate $validate
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login(AdminValidate $validate, Request $request): \think\Response
    {
        $data = $request->param();
        $result = $validate->scene('login')->check($data);
        if(!$result){
            return $this->notValidate($validate->getError());
        }
        // 转为小写
        $sessionCaptcha = strtolower(Cache::get('captcha'));
        $codeInput = strtolower($data['code']);
        if ($codeInput !== $sessionCaptcha) {
            return $this->notValidate('验证码错误');
        }
        $service = app()->make(AdminService::class);
        return $this->success(['token' => $service->login($data)]);
    }

    /**
     * 刷新 Token
     *
     * @param Request $request
     * @return \think\Response
     */
    public function refreshToken(Request $request): \think\Response
    {
        $token = $request->header('Authorization');

        if (!$token) {
            return $this->unauthorized('Token 缺失');
        }

        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }

        $newToken = JwtUtil::refreshToken($token);

        if (!$newToken) {
            return $this->unauthorized('Token 无效或已过期');
        }

        return $this->success(['token' => $newToken]);
    }

    /**
     * 验证码
     *
     * @return \think\Response
     */
    public function captcha(): \think\Response
    {
        // 创建验证码生成器
        $builder = new CaptchaBuilder;
        $builder->setBackgroundColor(220, 210, 230);// 设置背景颜色RGB
        $builder->build();
        // 将验证码内容存储到 Session 中
        Cache::set('captcha', $builder->getPhrase(), 3600);

        // 获取验证码图片的二进制数据并转换为 Base64 格式
        $imageData = $builder->get(); // 获取原始图片数据
        $base64Image = 'data:image/jpeg;base64,' . base64_encode($imageData);
        return $this->success(['captcha' => $base64Image]);
    }


    /**
     * 获取管理员信息
     *
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAdminInfo(Request $request): \think\Response
    {
        $admin_id = $request->userInfo['user_id'];
        $service = app()->make(AdminService::class);
        return $this->success($service->getAdminInfo($admin_id));
    }

    /**
     * 获取管理员菜单路由
     *
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getMenuRoutes(Request $request): \think\Response
    {
        $admin_id = $request->userInfo['user_id'];
        $service = app()->make(AdminService::class);
        return $this->success($service->getMenuRoutes($admin_id));
    }

    /**
     * 获取权限列表
     *
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPermissions(Request $request): \think\Response
    {
        $admin_id = $request->userInfo['user_id'];
        $service = app()->make(AdminService::class);
        return $this->success($service->getPermissions($admin_id));
    }
}